use crate::model::FudaThing;
use anyhow::Result;
use derive_more::Display;
use serde::Deserialize;
use serde::Serialize;
use surrealdb::sql::Thing;
use ts_rs::TS;

///
/// 指定证券的交易流水,真实交易流水，应该从交易软件同步过来
///
/// TradeTx->trade_tx_of->Security
/// 
/// security_id+settlement_date+transaction_time决定唯一
///
#[derive(Debug, Serialize, Deserialize, Default, TS, Clone)]
#[ts(export)]
pub struct TradeTx {
    /// 唯一标识符，security_id.tbot.klt.no e.g. SH.STOCK.600519.tbot.5.1
    #[ts(as = "Option<FudaThing>")]
    pub id: Option<Thing>,

    /// 证券ID，如SH.STOCK.600519
    pub security_id: String,

    /// 证券名称，采自《国信证券》成交记录详情
    pub security_name: Option<String>,
    /// 证券代码，采自《国信证券》成交记录详情
    pub security_code: Option<String>,
    /// 摘要信息，采自《国信证券》成交记录详情
    pub summary_info: Option<String>,
    /// 成交数量，采自《国信证券》成交记录详情
    pub trade_quantity: Option<u32>,
    /// 成交价格，采自《国信证券》成交记录详情
    pub trade_price: Option<f64>,
    /// 成交金额，采自《国信证券》成交记录详情
    pub trade_amount: Option<f64>,
    /// 发生金额，采自《国信证券》成交记录详情
    pub occurred_amount: Option<f64>,
    /// 信用委托类型，采自《国信证券》成交记录详情
    pub credit_delegation_type: Option<String>,
    /// 交收日期，采自《国信证券》成交记录详情
    pub settlement_date: String,
    /// 合同序号，采自《国信证券》成交记录详情
    pub contract_number: Option<String>,
    /// 交易市场，采自《国信证券》成交记录详情
    pub trading_market: Option<String>,
    /// 股东代码，采自《国信证券》成交记录详情
    pub shareholder_code: Option<String>,

    /// 结算汇率，采自《国信证券》成交记录详情
    pub exchange_rate: Option<f64>,
    /// 印花税，采自《国信证券》成交记录详情
    pub stamp_duty: Option<f64>,
    /// 净手续费，采自《国信证券》成交记录详情
    pub net_commission: Option<f64>,
    /// 过户费，采自《国信证券》成交记录详情
    pub transfer_fee: Option<f64>,
    /// 清算费，采自《国信证券》成交记录详情
    pub clearing_fee: Option<f64>,
    /// 交易规费，采自《国信证券》成交记录详情
    pub trading_fee: Option<f64>,
    /// 经手费，采自《国信证券》成交记录详情
    pub regulatory_fee: Option<f64>,
    /// 其他费用，采自《国信证券》成交记录详情
    pub other_fees: Option<f64>,
    /// 前台费，采自《国信证券》成交记录详情
    pub front_desk_fee: Option<f64>,
    /// 费用合计，采自《国信证券》成交记录详情
    pub total_fees: Option<f64>,

    /// 成交时间，采自《国信证券》成交记录详情
    pub settlement_time: String,
    /// 组合类型，采自《国信证券》成交记录详情
    pub combination_type: Option<String>,

    /// 记录更新日期 HLC
    pub last_updated: Option<String>,
}

impl TradeTx {
    pub fn id_from(
        security_id: &str,
        settlement_date: &str,
        settlement_time: &str,
    ) -> Result<String> {

        Ok(format!(
            "Ttx.{}.{}.{}",
            security_id, settlement_date, settlement_time
        ))
    }
}

/// k线类型，系统只支持预定义的k线类型，用户自定义的k线类型不支持
#[derive(Debug, Serialize, Deserialize, PartialEq, Display, TS, Clone, Copy, Eq, Hash)]
#[serde(rename_all = "UPPERCASE")]
#[ts(export)]
pub enum TradeTxType {
    /// buy
    BUY,
    /// sell
    SELL,
    /// none
    NONE,
}

impl Default for TradeTxType {
    fn default() -> Self {
        TradeTxType::NONE
    }
}
